package com.heba.greenmulu;

import android.content.ContentResolver;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.DrawableRes;

import com.heba.Cfg;
import com.heba.Debug;
import com.heba.config.CommonConfig;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.helper.WebViewHelper;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 文章详情页面
 * Created by jason on 2019/2/12.
 */

public class ItemArticleDetailActivity extends BaseActivity {

    private TextView txt_article;
    private TextView txt_author;
    private TextView txt_date;
    private ImageView img_collect;
    private WebView webView;

    private String articleID = "";
    private String title = "";
    private int isCollect = 0;   //是否收藏 0:否  1:是
    private String content = "";
    private String shareLink = "";   //文章分享链接

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item_article_detail);
        initTopbar();
        findViewById();
        initView();
        getArticleDetail();
    }

    @Override
    protected void findViewById() {
        txt_article = findViewById(R.id.txt_article);
        txt_author = findViewById(R.id.txt_author);
        txt_date = findViewById(R.id.txt_date);
        img_collect = findViewById(R.id.img_collect);
        webView = findViewById(R.id.webview);
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            articleID = bundle.getString(CommonConfig.ARTICLE_ID, "");
            title = bundle.getString(CommonConfig.ARTICLE_TITLE, getResources().getString(R.string.article));
        }
        txt_title.setText(title);

        /**
         * webview設置
         */
        WebViewHelper.Set(webView);
        webView.setWebViewClient(new MyWebViewClient());
        webView.setWebChromeClient(new MyWebChromeClient());

        /**
         * 调用系统分享
         */
        img_right.setOnClickListener(v -> {
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/*");
//            shareIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.share));//添加分享内容标题
            shareIntent.putExtra(Intent.EXTRA_TEXT, txt_article.getText().toString() + " " + shareLink);  //添加分享内容

            startActivity(Intent.createChooser(shareIntent, getResources().getString(R.string.share)));
        });

        /**
         * 收藏文章
         */
        img_collect.setOnClickListener(v -> {
            if (isCollect == 0) {
                new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                    @Override
                    public void Success() {
                        isCollect = 1;
                        img_collect.setSelected(true);
                    }

                    @Override
                    public void Fail(String error) {

                    }
                }).collectArticle(ItemArticleDetailActivity.this, articleID);
            } else {
                new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                    @Override
                    public void Success() {
                        isCollect = 0;
                        img_collect.setSelected(false);
                    }

                    @Override
                    public void Fail(String error) {

                    }
                }).uncollectArticle(ItemArticleDetailActivity.this, articleID);
            }
        });
    }

    /**
     * 主要帮助webview处理各种通知、请求事件
     */
    private class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {   //页面开始加载
//            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {   //页面加载完成
//            progressBar.setVisibility(View.GONE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //    return super.shouldOverrideUrlLoading(view, url);
            Debug.Log("shouldOverrideUrlLoading", "webview url拦截处理");
            openActivityFromUri(Intent.ACTION_VIEW, url);
//            view.loadUrl(url);
            return true;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            //     super.onReceivedError(view, errorCode, description, failingUrl);
            //  Toast.makeText(this,"网页加载错误！",0).show();
        }
    }

    /**
     * 主要帮助webview处理JavaScript对话框、加载进度、网站图标、网站icon等
     */
    private class MyWebChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
//            super.onProgressChanged(view, newProgress);
//            progressBar.setProgress(newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            super.onReceivedIcon(view, icon);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }
    }

    /**
     * 获取文章详情
     */
    private void getArticleDetail() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("ArticleID", articleID);
        client.get(Cfg.BaseUrl + "/Article/Detail", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        try {
                            JSONObject json = new JSONObject(response.trim());
                            JSONObject object = json.getJSONObject("Result");
                            txt_article.setText(object.getString("Title"));
                            txt_author.setText(object.getString("Publisher"));
                            txt_date.setText(object.getString("TimeCreated"));
                            isCollect = object.getInt("IsCollect");
                            content = object.getString("Content");
                            if (object.has("Link")) {
                                shareLink = object.getString("Link");
                            }
                            img_collect.setSelected(isCollect == 0 ? false : true);
                            webView.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }

    /**
     * 图片id转为uri
     *
     * @param id
     * @return
     */
    private String getResourcesUri(@DrawableRes int id) {
        Resources resources = getResources();
        String uriPath = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
                resources.getResourcePackageName(id) + "/" +
                resources.getResourceTypeName(id) + "/" +
                resources.getResourceEntryName(id);
        Toast.makeText(this, "Uri:" + uriPath, Toast.LENGTH_SHORT).show();
        return uriPath;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webView != null)
            webView = null;
    }
}
